package com.example.demo.controller.impor;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelReader {
    public static List<UserExcelData> readExcel(InputStream is) throws IOException {
        List<UserExcelData> dataList = new ArrayList<>();
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        XSSFSheet sheet = workbook.getSheetAt(0);

        for (Row row : sheet) {
            if (row.getRowNum() == 0) continue; // 跳过标题行
            UserExcelData data = new UserExcelData();
            data.setUser(getCellValue(row.getCell(0)));
            data.setContact(getCellValue(row.getCell(1)));
            data.setDept1(getCellValue(row.getCell(2)));
            data.setDept2(getCellValue(row.getCell(3)));
            dataList.add(data);
        }
        workbook.close();
        return dataList;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING: return cell.getStringCellValue();
            case NUMERIC: return String.valueOf(cell.getNumericCellValue());
            default: return "";
        }
    }
}
